<template>
  <div>
    <a-card>
      <a-space>
        <a-input
          v-model:value="listQuery.keyword"
          placeholder="输入条件关键字搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-input
          v-model:value="listQuery.content"
          placeholder="输入条件高危内容搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-input
          v-model:value="listQuery.aiResult"
          placeholder="输入条件AI判定结果搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-input
          v-model:value="listQuery.fileType"
          placeholder="输入条件文件类型搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-input
          v-model:value="listQuery.filePath"
          placeholder="输入条件文件路径搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-input
          v-model:value="listQuery.serverFilePath"
          placeholder="输入条件云端文件路径搜索"
          allow-clear
          @keyup.enter="handleFilter"
        />
        <a-button type="primary" :icon="h(SearchOutlined)" @click="handleFilter">搜索</a-button>
      </a-space>
    </a-card>
    <a-card class="mt-2">
      <!--      <a-button type="primary" class="mb-4" :icon="h(PlusOutlined)" @click="handleAdd">-->
      <!--        添加-->
      <!--      </a-button>-->
      <a-table
        bordered
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :loading="tableLoading"
        :row-key="(row) => row.id + ''"
      >
        <template #bodyCell="{ column, record }">

          <template v-if="column.dataIndex === 'keyword'">
            <a-tooltip placement="top">
              <template #title>{{ record.keyword }}</template>
              {{ record.keyword.slice(0, 20) }}
            </a-tooltip>
          </template>
          <template v-if="column.dataIndex === 'aiResult'">
            <a-tooltip placement="top">
              <template #title>{{ record.aiResult }}</template>
              {{ record.aiResult.slice(0, 20) }}
            </a-tooltip>
          </template>


          <template v-if="column.dataIndex === 'content'">
            <a-tooltip placement="top">
              <template #title>{{ record.content }}</template>
              {{ record.content.slice(0, 20) }}
            </a-tooltip>
          </template>

          <template v-if="column.dataIndex === 'actions'">
            <a-button size="small" type="link" @click="handleAI(record)">AI重新鉴定</a-button>
            <a-button size="small" type="link" @click="handleDownload(record)">下载原始文件
            </a-button>
            <a-button size="small" type="link" danger @click="handleDelete(record)">删除</a-button>
          </template>


        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="showModal" :mask-closable="false" :title="title">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 5 }"
        style="padding-top: 20px"
      >
        <a-form-item label="" name="id">
          <a-input v-model:value="form.id" allow-clear placeholder="请输入"/>
        </a-form-item>
        <a-form-item label="关键字" name="keyword">
          <a-input v-model:value="form.keyword" allow-clear placeholder="请输入关键字"/>
        </a-form-item>
        <a-form-item label="高危内容" name="content">
          <a-input v-model:value="form.content" allow-clear placeholder="请输入高危内容"/>
        </a-form-item>
        <a-form-item label="AI判定结果" name="aiResult">
          <a-input v-model:value="form.aiResult" allow-clear placeholder="请输入AI判定结果"/>
        </a-form-item>
        <a-form-item label="文件类型" name="fileType">
          <a-input v-model:value="form.fileType" allow-clear placeholder="请输入文件类型"/>
        </a-form-item>
        <a-form-item label="文件路径" name="filePath">
          <a-input v-model:value="form.filePath" allow-clear placeholder="请输入文件路径"/>
        </a-form-item>
        <a-form-item label="文件大小" name="fileSize">
          <a-input v-model:value="form.fileSize" allow-clear placeholder="请输入文件大小"/>
        </a-form-item>
        <a-form-item label="创建时间" name="createTime">
          <a-input v-model:value="form.createTime" allow-clear placeholder="请输入创建时间"/>
        </a-form-item>
        <a-form-item label="云端文件路径" name="serverFilePath">
          <a-input v-model:value="form.serverFilePath" allow-clear
                   placeholder="请输入云端文件路径"/>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" :loading="formBtnLoading" @click="handleConfirm">提交</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {h, onMounted, reactive, ref} from 'vue';
import TableFileApi from '@/api/TableFileApi';
import {PlusOutlined, SearchOutlined} from '@ant-design/icons-vue';
import {message, Modal} from 'ant-design-vue';
import {Rule} from 'ant-design-vue/es/form';
import {resetReactive} from '@/utils';

let columns = [
  {title: '', dataIndex: 'id', ellipsis: true,},
  {title: '关键字', dataIndex: 'keyword',},
  {title: '高危内容', dataIndex: 'content',},
  {title: 'AI判定结果', dataIndex: 'aiResult'},
  {title: '文件类型', dataIndex: 'fileType', ellipsis: true,},
  {title: '文件路径', dataIndex: 'filePath', ellipsis: true,},
  {title: '文件大小', dataIndex: 'fileSize', ellipsis: true,},
  {title: '创建时间', dataIndex: 'createTime', ellipsis: true,},
  {title: '云端文件路径', dataIndex: 'serverFilePath', ellipsis: true,},
  {
    title: '操作',
    dataIndex: 'actions',
    align: 'center',
  },
];
let data = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (current, pageSize) => {
    pagination.current = current;
    pagination.pageSize = pageSize;
    getList();
  },
});
onMounted(() => {
  getList();
});

const listQuery = reactive<any>({});

const tableLoading = ref(false);

function getList() {
  tableLoading.value = true;
  TableFileApi.page({index: pagination.current, size: pagination.pageSize, ...listQuery})
    .then((res) => {
      data.value = res.data;
      pagination.total = res.total;
    })
    .finally(() => (tableLoading.value = false));
}


function handleAI(raw) {
  TableFileApi.reqAi(raw.id).then(res => {
    message.success('AI正在分析');
  })

}


function handleFilter() {
  pagination.current = 1;
  getList();
}

const showModal = ref(false);
const title = ref('');
const formRef = ref();
let form = reactive<any>({});
const rules: Record<string, Rule[]> = {
  name: [{required: true, trigger: 'blur', message: '请输入'}],
};

function handleEdit(row) {
  showModal.value = true;
  title.value = '编辑';
  Object.assign(form, row);
  formRef.value?.clearValidate();
}

function handleDownload(row) {
  TableFileApi.getFile(row.serverFilePath)
    .then(response => {
      // 创建一个 URL 对象并为 blob 创建一个下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      // 创建一个 <a> 标签来触发下载
      const link = document.createElement('a');
      link.href = url;
      let filename = 'downloaded_file'; // 默认文件名
      const contentDisposition = response.headers['content-disposition'];
      if (contentDisposition && contentDisposition.indexOf('filename=') !== -1) {
        // 从 content-disposition 提取文件名
        const matches = /filename="([^"]+)"/.exec(contentDisposition);
        if (matches && matches[1]) {
          filename = matches[1];
        }
      }
      link.setAttribute('download', filename); // 设置下载文件的名称
      document.body.appendChild(link);
      link.click(); // 触发点击事件下载文件
      document.body.removeChild(link); // 下载后移除 <a> 标签
    })
    .catch(error => {
      console.error('下载文件失败:', error);
    });
}

function handleAdd() {
  showModal.value = true;
  title.value = '添加';
  resetReactive(form);
  formRef.value?.clearValidate();
}

const formBtnLoading = ref(false);

function handleConfirm() {
  formRef.value
    .validate()
    .then(() => {
      formBtnLoading.value = true;
      (form.id ? TableFileApi.update(form) : TableFileApi.save(form))
        .then(() => {
          message.success('提交成功');
          showModal.value = false;
          getList();
        })
        .finally(() => {
          formBtnLoading.value = false;
        });
    })
    .catch(() => {
    });
}

function handleDelete(row) {
  Modal.confirm({
    title: '提示',
    content: '确定删除这条记录吗',
    onOk() {
      TableFileApi.delete([row.id]).then(() => {
        message.success('操作成功');
        getList();
      });
    },
    onCancel() {
    },
  });
}
</script>

<style scoped></style>
